var express = require("express");
var adminRouter = express.Router();
const formatRsponse = require("../utils/responseFormat");
const admin = require("../service/adminService");
const tool = require("../utils/tool");
const { ValidationError } = require("../utils/errors");
//登录
adminRouter.post("/login", async (req, res, next) => {
  //验证码验证
  if (req.body.captcha.toLowerCase() !== req.session.captcha.toLowerCase()) {
    throw new ValidationError("验证码错误");
  }

  //账号密码验证
  const result = await admin.loginService(req.body);
  if (result.token) {
    res.header("authorization", result.token);
  }

  res.send(formatRsponse(0, "", result.data));
});

//恢复登录状态
adminRouter.get("/whoami", async (req, res, next) => {
  //获取token
  const result = tool.analysisToken(req.headers.authorization);
  //验证token

  res.send(
    formatRsponse(0, "", {
      id: result.id,
      name: result.name,
      loginId: result.loginId,
    })
  );
});

//修改管理员信息
adminRouter.put("/", async (req, res, next) => {
  const data = await admin.updateService(req.body);
  res.send(formatRsponse(0, "", data));
});

module.exports = adminRouter;
